import React, { useState, useEffect, useRef } from 'react';
import './qbfl.css';
import { useNavigate } from 'react-router-dom';
import { NavBar, SideBar } from 'antd-mobile';
import axios from 'axios';

const Qbfl = () => {
    const navigate = useNavigate();
    const items = [
        { key: '1', title: '热销爆款' },
        { key: '2', title: '大牌专区' },
        { key: '3', title: '智能手环' },
        { key: '4', title: '智能秤' },
        { key: '5', title: '睡眠管理' },
        { key: '6', title: '营养健康' },
        { key: '7', title: '护理清洁' },
        { key: '8', title: '智能手表' },
        { key: '9', title: '血压计' },
        { key: '10', title: '运动户外' },
        { key: '11', title: '配件及其他' }
    ];

    // 获取列表数据
    const [list, setlist] = useState([]);
    const getlist = () => {
        axios.get('http://localhost:3000/chen_getlist')
            .then(res => {
                setlist(res.data.data);
            })
            .catch(error => {
                console.error('获取数据失败:', error);
            });
    };

    useEffect(() => {
        getlist();
    }, []);

    // 监听滚动事件
    const mainElementRef = useRef(null);
    const [activeKey, setActiveKey] = useState('1'); // 初始选中第一个分类

    useEffect(() => {
        const handleScroll = () => {
            if (mainElementRef.current) {
                const scrollTop = mainElementRef.current.scrollTop;
                let currentActiveKey = null;
                items.forEach((item, index) => {
                    const element = document.getElementById(`anchor-${item.key}`);
                    if (element) {
                        const rect = element.getBoundingClientRect();
                        // 判断元素顶部距离视口顶部的距离是否小于等于 0
                        // 并且（是最后一个元素 或者 下一个元素顶部距离视口顶部大于 0）
                        if (rect.top <= 0 && (index === items.length - 1 || document.getElementById(`anchor-${items[index + 1].key}`).getBoundingClientRect().top > 0)) {
                            currentActiveKey = item.key;
                        }
                    }
                });
                if (currentActiveKey) {
                    setActiveKey(currentActiveKey);
                }
            }
        };

        if (mainElementRef.current) {
            mainElementRef.current.addEventListener('scroll', handleScroll);
        }

        return () => {
            if (mainElementRef.current) {
                mainElementRef.current.removeEventListener('scroll', handleScroll);
            }
        };
    }, [items]);

    // 获取商品列表
    const getProductList = (category) => {
        if (category === '手环' || category === '秤' || category === '计') {
            return list.filter(product => product.name.includes(category));
        } else {
            const shuffled = [...list].sort(() => 0.5 - Math.random());
            return shuffled.slice(0, 3);
        }
    };

    // 处理商品名称过长的函数
    const handleProductName = (name) => {
        return name.length > 8 ? `${name.slice(0, 8)}...` : name;
    };

    // 处理侧边栏点击事件
    const handleSideBarClick = (key) => {
        setActiveKey(key);
        const targetElement = document.getElementById(`anchor-${key}`);
        if (targetElement && mainElementRef.current) {
            const offsetTop = targetElement.offsetTop;
            mainElementRef.current.scrollTop = offsetTop;
        }
    };

    return (
        <div style={{ background: "white" }}>
            <NavBar onBack={() => navigate(-1)} className='qbfl-nav'>全部分类</NavBar>
            <div className='qbfl-div'>
                <SideBar className='qbfl-div1'>
                    {items.map(item => (
                        <SideBar.Item
                            key={item.key}
                            title={item.title}
                            className={item.key === activeKey ? 'active' : 'default'}
                            onClick={() => handleSideBarClick(item.key)}
                        />
                    ))}
                </SideBar>
                <div className="qbfl-div2" ref={mainElementRef} style={{ overflow: 'auto' }}>
                    {items.map(item => (
                        <div key={item.key}>
                            <h2 id={`anchor-${item.key}`}>{item.title}</h2>
                            <div className='qbfl-div3'>
                                {getProductList(item.title).map(product => (
                                    <div key={product.id} className='qbfl-div4'>
                                        <img src={product.img} alt={product.name} className='qbfl-img' />
                                        <p>{handleProductName(product.name)}</p>
                                    </div>
                                ))}
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
};

export default Qbfl;